<?php
namespace app\operator\controller;
use think\Db;
use think\Cache;
class Login extends Common
{
	//扫描
    public function scancodelogin()
    {

    	$newkey = input('param.key');
        $openid = mwdecrypt(input('param.openid'));
        if(!$newkey){
            die('非法请求！');
        }
        $newkey = mwdecrypt($newkey);  //解密key
        $newkey = explode("|",$newkey);  //转为字符串

        if(count($newkey)!=2){
            $info['code'] = 0;
            $info['msg'] = '二维码错误！';
            return $info;
        }
        $key = $newkey[0];
        $time = $newkey[1];
        $data = Cache::get($key);
        if(!$data){
            $info['code'] = 0;
            $info['msg'] = '二维码已失效！';
            return $info;
        }
        if(isset($data['scancode'])){
            $info['code'] = 0;
            $info['msg'] = '请不要重复扫描！';
            return $info;
        }
        $user = Db::name('operator_users')->where(['openid'=>$openid,'deleted'=>0])->field('id,oid,username')->select();
        if(!$user){
            $info['code'] = 2;
            $info['msg'] = '未绑定运营商！';
            return $info;
        }

        $data['scancode']=true;
        Cache::set($key,$data,120);


        if(count($user)>1){
            $info['operator']=[];
            foreach ($user as $key => $value) {
                $oid = $value['oid'];
                $operator = Db::name('operator')->where(['id'=>$oid,'deleted'=>0])->field('id,name')->find();
                if($operator){
                    $info['operator'][] = $operator;
                }
            }
            $info['data'] = $data;
            $info['count'] =count($info['operator']);
            $info['user'] = $user;
            $info['code'] = 1;
            return $info;

        }else{

            $info['count'] = 1;
            $info['user'] = $user[0];
            $info['data'] = $data;
            $info['code'] = 1;
            return $info;
        }

    }

    //登陆
    public function dologin(){
        $input = input('param.');
        $openid = mwdecrypt($input['openid']);  
        $user = $input['user'];
        $newkey = $user['key'];

        $newkey = mwdecrypt($newkey);  //解密key
        $newkey = explode("|",$newkey);  //转为字符串

        if(count($newkey)!=2){
            $info['code'] = 0;
            $info['msg'] = 'key错误！';
            return $info;
        }
        $key = $newkey[0];
        $time = $newkey[1];

        $data = Cache::get($key);
        if($data){

            $data['uid'] = $user['id'];
            $data['oid'] = $user['oid'];
            $data['username'] = $user['username'];
            Cache::set($key,$data,120);  //将KEY写入缓存

            $info['data'] = $data;
            $info['key'] = $key;
            $info['code'] = 1;
            return $info;
        }else{
            $info['code'] = 0;
            $info['msg'] = '登陆信息已失效，请重新扫码！';
            return $info;
        }
        



    }

}
